# 加载文件和数据
include("formula.jl")
formula = loadformula()

# 设置参数
querylist=[ "红瓶", "绿瓶", "灰瓶", "蓝瓶", "紫瓶", "黄瓶" ]
querynum = [ 1, 1, 1, 1, 1, 1 ]
productweight = 1
filename = "example"

# 查询每个项目的合成路径
f = open( filename*"_.csv", "w" )
g = open( filename*".txt", "w" )
for i=1:length(querylist)
    queryproducepath( querylist[i], querynum[i], formula, f, indentadd="")
    queryproducepath( querylist[i], querynum[i], formula, g, indentadd="  |")
end
close(f)
close(g)

# 读入查询到的清单
f = open( filename*"_.csv", "r" )
l = readlines(f)
close(f)

# 将清单中的数量由字符串转换为分数
name = []
num = []
for i=1:length(l)
    t = split(l[i],",")
    global name = [name; t[1]]
    if occursin("/", t[2])
        r = split(t[2], '/', keepempty=false)
        tn = Rational{Int32}(parse(Float64, r[1])/parse(Float64, r[2]))
    else
        tn = Rational{Int32}(parse(Float64,t[2]))
    end
    global num = [num; tn]
end

# 合并相同的项
global item = unique(name)
sort!(item)
global cost = zeros(Rational, length(item))
for i=1:length(item)
    iname = item[i]
    for j=1:length(name)
        if name[j]==iname
            cost[i] += num[j]
        end
    end
end

# 将合并后的数据写入文件,并计算需要的组装机数量
g = open(filename*".csv","w")
for i=1:length(item)
    it = item[i]
    vp = cost[i]
    if denominator(vp) == 1
        vp = numerator(vp)
    end
    x=queryproduct(it ,formula)
    t=x[1].cost
    n=x[1].productNum[1]
    if typeof(t)==Float64
        co = Int(ceil(vp/n*t/productweight))
    else
        co = t
    end
    print(g,"$it,$vp,$co\n")
end
close(g)
rm(filename*"_.csv")
